//
//  Light.m
//  CompGraf2
//
//  Created by Juan Niosi on 30/08/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Light.h"
#import "World.h"

@implementation Light

@synthesize attenuation, lightIndex, spotAngle, spotDir, spotExp;

- (id)init:(GLenum)lightEnum
{
    self = [super init];
    if (self) {
        
        lightIndex = lightEnum;
        spotLight = false;
        attenuation = 0.0f;
    }
    
    return self;
}

- (id)initSpot:(GLenum)lightEnum setAngle:(float)angle
{
    self = [self init:lightEnum];
    if (self)
    {
        spotLight = true;
        spotAngle = angle;
        spotExp = 0.0f;
        spotDir = malloc(sizeof(GLfloat)*3);
        spotDir[0] = 0.0f;
        spotDir[1] = -1.0f;
        spotDir[2] = 0.0f;
    }
    
    return self;
}


- (void)update:(float)deltaTime
{
    [super update:deltaTime];
    if (lightIndex == GL_LIGHT0)
    {
        GLfloat *charPos = [World getWorld].mainCharacter.position;
        self.position[0] = charPos[0];
        self.position[2] = charPos[2];
    }
}

- (void)draw:(Engine *)engine:(Camera *)cam;
{   
    [self applyTransform:engine];
    
    if (spotLight)
    {
        [engine drawSpotLight:lightIndex setPos:lightPos setAmbient:ambient setDiffuse:diffuse setSpecular:specular setAttenuation:attenuation setAngle:spotAngle setDir:spotDir setExponent:spotExp];
    }
    else
    {
        [engine drawLight:lightIndex setPos:lightPos setAmbient:ambient setDiffuse:diffuse setSpecular:specular setAttenuation:attenuation];
    }
    
    [self resetTransform:engine];

}

- (void)setLightPos:(GLfloat *)pos
{
    if (lightPos != NULL)
        free(lightPos);
    lightPos = pos;
}

- (GLfloat *)getLightPos
{
    return lightPos;
}

- (void)setDiffuse:(GLfloat *)dif
{
    if (diffuse != NULL)
        free(diffuse);
    diffuse = dif;
}

- (GLfloat *)getDiffuse
{
    return diffuse;
}

- (void)setAmbient:(GLfloat *)amb
{
    if (ambient != NULL)
        free(ambient);
    ambient = amb;
}

- (GLfloat *)getAmbient
{
    return ambient;
}

- (void)setSpecular:(GLfloat *)spec
{
    if (specular != NULL)
        free(specular);
    specular = spec;
}

- (GLfloat *)getSpecular
{
    return specular;
}

- (void)dealloc
{
    if (lightPos != NULL)
        free(lightPos);
    if (diffuse != NULL)
        free(diffuse);
    if (ambient != NULL)
        free(ambient);
    if (specular != NULL)
        free(specular);
    if (spotDir != NULL)
        free(spotDir);
    
    [super dealloc];
}
@end
